/* ***** BEGIN LICENSE BLOCK *****
 * Version: NPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Netscape Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/NPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is lutsko.com code.
 *
 * The Initial Developer of the Original Code is 
 * James Lutsko.
 * Portions created by the Initial Developer are Copyright (C) 2003
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the NPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the NPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

package autoschedule.ui;

import java.io.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.text.*;
import java.net.URL;
import javax.swing.JSplitPane;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.tree.TreePath;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import login.ui.LoginFrame;

import controller.RSMSController;

import autoschedule.*;
import autoteam.Local;
import autoteam.ui.AutoTeamFileFilter;

import autoschedule.ui.GCalendar;

/**
 * AutoScheduleDeskTop is the top-level window of the AutoSchedule application.
 * It contains the main function, sets up the menus and provides the menu
 * callbacks.
 * 
 * @author Jim Lutsko
 * @version %Revision$, $Date: 2005/03/09 09:39:22 $
 * @since 1.0
 */

public class AutoScheduleDeskTop extends JFrame implements ActionListener,
    TreeSelectionListener, FileHistory.IFileHistory
{
  /**
   * We keep the filechooser so that it can be re-used.
   */
  JFileChooser fc = null;

  JMenu fileMenu = null;
  /**
   * The menu items for the file menu. The menu callback determines the menu
   * item chosen by comparing the passed object to these guys.
   */

  JMenuItem fileOpen, fileNew, fileLogout;
  /**
   * The menu items for the Options menu. The menu callback determines the menu
   * item chosen by comparing the passed object to these guys.
   */
  JMenuItem clearLog, saveLog, changeLeague;
  JCheckBoxMenuItem useTimeStamp, useFileVersion;

  /**
   * Menu items for Facilities menu.
   */
  JMenuItem facAdd, facDel, facRename, leagueAdd, leagueDel, leagueRename,
      scheduleClear, scheduleUnschedule, scheduleAddGame, scheduleDeleteGame;

  /**
   * The menu items for the Help menu. The menu callback determines the menu
   * item chosen by comparing the passed object to these guys.
   */
  JMenuItem helpHelp, helpAbout;

  /**
   * The about box - so we don't have to create it more than once.
   */
  JDialog aboutBox = null;

  /**
   * The help box - so we don't have to create it more than once.
   */
  JDialog helpBox = null;

  AutoScheduleFrame frame = null;
  JSplitPane splitPane = null;

  ScheduleTree st = null;
  AutoScheduleDoc doc = null;
  FileHistory fileHistory = null;
  RSMSController RSMSController = null;
  
  int width, height;
  // Optionally play with line styles. Possible values are
  // "Angled" (the default), "Horizontal", and "None".
  private static boolean playWithLineStyle = false;
  private static String lineStyle = "Horizontal";

  private final int frameWidth = 640;
  private final int frameHeight = 480;
  private final Dimension frameSize = new Dimension(frameWidth, frameHeight);

  private Toolkit sizer = Toolkit.getDefaultToolkit(); 
  private Dimension screenSize = sizer.getScreenSize();

  private final int screenCenterX = (screenSize.width-frameWidth)/2;
  private final int screenCenterY = (screenSize.height-frameHeight)/2;

  // Optionally set the look and feel.
  private static boolean useSystemLookAndFeel = false;

  /**
   * The sole constructor. The desktop is initialized and the menus built.
   */
  public AutoScheduleDeskTop()
  {
    super(Local.get("ScheduleProgramName"));
    
    createMenus();

    // Setup the file history
    //
    fileHistory = new FileHistory(this); // init FileHistory with our frame
    // as the only parameter.
    fileHistory.initFileMenuHistory(); // Start file history initialization.

    // Setup the exit method
    //
    this.addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent e)
      {
        exit();
      }
    });

    this.setBackground(Color.white);

    // Create a split pane with the two scroll panes in it.
    //
    splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);

    // create the tree
    //
    st = new ScheduleTree();

    // Listen for when the selection changes.
    //
    st.tree.addTreeSelectionListener(this);

    if (playWithLineStyle)
    {
      System.out.println("line style = " + lineStyle);
      st.tree.putClientProperty("JTree.lineStyle", lineStyle);
    }

    // Create the scroll pane and add the tree to it.
    //
    JScrollPane treeView = new JScrollPane(st.getTree());

    this.setSize(frameSize);
    this.setMinimumSize(frameSize);
    this.setLocation(screenCenterX,  screenCenterY);

    frame = new AutoScheduleFrame(null);
    frame.setVisible(true); // necessary as of 1.3

    splitPane.setTopComponent(treeView);
    splitPane.setBottomComponent(frame);
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(150);
   
    this.setContentPane(splitPane);
    this.setVisible(true);
  }

  public AutoScheduleDeskTop(RSMSController controller)
  {
    this();
    this.RSMSController = controller;
  }

  /**
   * Close the frame, save the file history entries, and exit.
   */
  private void exit()
  {
    setVisible(false);
    dispose();
    fileHistory.saveHistoryEntries(); // Save pathname entries for next
    // session.
    System.exit(0);
  }

  // ////////////////////////////////////////////////////////////////////////////////////
  // Implement the IFileHistory interface
  //
  // ////////////////////////////////////////////////////////////////////////////////////

  /**
   * Get the application name to identify the configuration file in the the
   * USER_HOME directory. This name should be unique in this directory.
   * 
   * @return the application name.
   */
  public String getApplicationName()
  {
    return new String("RSMS_Scheduler");
  }

  /**
   * Get a handle to the frame's File menu.
   * 
   * @return the frame's File menu.
   */
  public JMenu getFileMenu()
  {
    return fileMenu;
  }

  /**
   * Return the size of the main application frame. It is used to center the
   * File History maintenance window.
   * 
   * @return the main GUI frame's size.
   */
  public Dimension getSize()
  {
    return super.getSize();
  }

  /**
   * Return the main application frame. It is used to center the file history
   * maintenance window.
   * 
   * @return the main GUI frame instance.
   */
  public JFrame getFrame()
  {
    return this;
  }
  /**
   * Perform the load file activity.
   * 
   * @param path
   *          is the pathname of the loaded file.
   */
  public void loadFile(String pathname)
  {
    doOpen(new File(pathname));
    // String filename =
    // path.substring(path.lastIndexOf(FILE_SEPARATOR_STR)+1,
    // path.length());
    // if (filename.length() > 30) {
    // filename = filename.substring(0, 30) + "...";
    // }
  }
  /**
   * setParent sets the RSMSController for this JFrame
   * 
   * @author Colin Watson
   * @version %Revision$, $Date: 2010/10/17 2:40 $
   */

  public void setParent(RSMSController temp)
  {
    RSMSController = temp;
  }

  // ////////////////////////////////////////////////////////////////////////////////////

  public void valueChanged(TreeSelectionEvent e)
  {
    TreePath tp = e.getPath();
    boolean fenabled = false;
    boolean lenabled = false;
    boolean senabled = false;

    if (tp != null)
    {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp
          .getLastPathComponent();

      if (node != null && node.getUserObject() != null)
      {
        if (node.getUserObject() instanceof Facility)
        {
          fenabled = true;
          if (frame != null)
            frame.showFacility((Facility) (node.getUserObject()), st
                .isScheduleNode(node));
        }
        else if (node.getUserObject() instanceof League)
        {
          lenabled = true;
          if (frame != null)
            frame.showLeague((League) (node.getUserObject()), st
                .isScheduleNode(node));
        }
        else if (node.getUserObject() instanceof Team)
        {
          if (frame != null)
            frame.showTeam((Team) (node.getUserObject()), st
                .isScheduleNode(node));
        }
        else if (node.getUserObject().equals("Reports"))
        {
          if (frame != null)
            frame.showReport();
        }
        else if (node.getUserObject().equals("Games Calendar"))
          frame.showCalendar();

        if (node.getUserObject().equals("Schedules") || st.isScheduleNode(node))
        {
          senabled = true;
          if (frame != null)
            frame.showSchedule();
        }

      }
      else if (frame != null)
        frame.showCalendar();
    }

    facDel.setEnabled(fenabled);
    facRename.setEnabled(fenabled);
    leagueDel.setEnabled(lenabled);

    scheduleClear.setEnabled(senabled);
    scheduleAddGame.setEnabled(senabled);
    scheduleUnschedule.setEnabled(senabled);
    scheduleDeleteGame.setEnabled(senabled);

    leagueRename.setEnabled(lenabled);
  }

  /**
   * Make the menus
   */
  void createMenus()
  {
    // Create the menu bar.
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    // Build the first menu.
    JMenu menu = new JMenu(Local.get("File"));
    fileMenu = menu;
    menu.setMnemonic(KeyEvent.VK_F);
    menuBar.add(menu);

    fileOpen = new JMenuItem(Local.get("Open"), KeyEvent.VK_O);
    fileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    fileOpen.addActionListener(this);
    menu.add(fileOpen);

    fileNew = new JMenuItem("New", KeyEvent.VK_N);
    fileNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    fileNew.addActionListener(this);
    menu.add(fileNew);

    JMenuItem fileSave = new JMenuItem(Local.get("Save"), KeyEvent.VK_S);
    fileSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    // fialeSave.addActionListener(this);
    fileSave.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        saveData();
      }
    });
    menu.add(fileSave);

    JMenuItem fileSaveAs = new JMenuItem(Local.get("SaveAs"), KeyEvent.VK_A);
    fileSaveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    // fileSaveAs.addActionListener(this);
    fileSaveAs.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        saveDataAs();
      }
    });
    menu.add(fileSaveAs);

    fileLogout = new JMenuItem("Logout");
    fileLogout.addActionListener(this);
    fileLogout.setEnabled(true);
    menu.add(fileLogout);

    menu.addSeparator();

    JMenuItem fileClose = new JMenuItem(Local.get("Close"), KeyEvent.VK_C);
    fileClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    fileClose.addActionListener(this);
    fileClose.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        closeWindow();
      }
    });
    menu.add(fileClose);

    JMenuItem fileExit = new JMenuItem(Local.get("Exit"), KeyEvent.VK_X);
    fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    fileExit.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        exit();
      }
    });

    menu.add(fileExit);

    // Build the Facilities menu.
    menu = new JMenu("Edit");

    menu.setMnemonic(KeyEvent.VK_E);
    menuBar.add(menu);

    facAdd = new JMenuItem("Add Facility", KeyEvent.VK_A);
    facAdd.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    facAdd.addActionListener(this);
    menu.add(facAdd);

    facDel = new JMenuItem("Delete Facility", KeyEvent.VK_D);
    facDel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    facDel.addActionListener(this);
    facDel.setEnabled(false);
    menu.add(facDel);

    facRename = new JMenuItem("Rename Facility", KeyEvent.VK_R);
    facRename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    facRename.addActionListener(this);
    facRename.setEnabled(false);
    menu.add(facRename);

    menu.addSeparator();

    leagueAdd = new JMenuItem("Add League", KeyEvent.VK_A);
    leagueAdd.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    leagueAdd.addActionListener(this);
    menu.add(leagueAdd);

    leagueDel = new JMenuItem("Delete League", KeyEvent.VK_D);
    leagueDel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    leagueDel.addActionListener(this);
    leagueDel.setEnabled(false);
    menu.add(leagueDel);

    leagueRename = new JMenuItem("Rename League", KeyEvent.VK_R);
    leagueRename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    leagueRename.addActionListener(this);
    leagueRename.setEnabled(false);
    menu.add(leagueRename);

    menu.addSeparator();

    menu = new JMenu("Schedule");
    menu.setMnemonic(KeyEvent.VK_S);
    menuBar.add(menu);

    JMenuItem menuItem = new JMenuItem("Schedule Now", KeyEvent.VK_S);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    menuItem.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        if (doc != null)
          doc.schedule();
          ((GCalendar) frame.calendarPanel).refreshCalendar();
          
      }
    });
    menu.add(menuItem);

    scheduleClear = new JMenuItem("Clear Schedule", KeyEvent.VK_C);
    scheduleClear.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    scheduleClear.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        if (doc != null)
          doc.clearSchedule();
      }
    });
    scheduleClear.setEnabled(true);
    menu.add(scheduleClear);

    menu.addSeparator();

    scheduleAddGame = new JMenuItem("Add Game Game", KeyEvent.VK_U);
    // scheduleClear.setAccelerator(KeyStroke.getKeyStroke(
    // KeyEvent.VK_S, ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    scheduleAddGame.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        DefaultMutableTreeNode node = st.getSelectedNode();
        if (node != null && st.isScheduleNode(node)
            && (st.getSelectedLeague() != null))
        {
          League league = st.getSelectedLeague();
          // if(GameEditor.showDialog(null,doc,league))
          {
            // todo
          }

        }
        else
        {
          JOptionPane.showMessageDialog(null, "No league selected",
              "Cannot proceed ...", JOptionPane.INFORMATION_MESSAGE, null);
        }
      }
    });
    scheduleAddGame.setEnabled(true);
    menu.add(scheduleAddGame);

    scheduleDeleteGame = new JMenuItem("DeleteGame Game", KeyEvent.VK_U);
    // scheduleClear.setAccelerator(KeyStroke.getKeyStroke(
    // KeyEvent.VK_S, ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    scheduleDeleteGame.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        int i = frame.scheduleTablePanel.getSelectedRow();
        if (i < 0)
        {
          JOptionPane.showMessageDialog(null, "No game selected",
              "Cannot proceed ...", JOptionPane.INFORMATION_MESSAGE, null);
        }
        else if (doc != null)
        {
          Game g = (Game) frame.scheduleTableModel.getSelectedObject(i);
          doc.deleteGame(g);
        }
      }
    });
    scheduleDeleteGame.setEnabled(true);
    menu.add(scheduleDeleteGame);

    scheduleUnschedule = new JMenuItem("Unschedule Game", KeyEvent.VK_U);
    // scheduleClear.setAccelerator(KeyStroke.getKeyStroke(
    // KeyEvent.VK_S, ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    scheduleUnschedule.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        int i = frame.scheduleTablePanel.getSelectedRow();
        if (i < 0)
        {
          JOptionPane.showMessageDialog(null, "No game selected",
              "Cannot proceed ...", JOptionPane.INFORMATION_MESSAGE, null);
        }
        else if (doc != null)
        {
          Game g = (Game) frame.scheduleTableModel.getSelectedObject(i);
          doc.unScheduleGame(g);
        }
      }
    });
    scheduleUnschedule.setEnabled(true);
    menu.add(scheduleUnschedule);

    menu.addSeparator();

    menuItem = new JMenuItem("Export All", KeyEvent.VK_A);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    menuItem.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        if (doc != null)
        {
          doc.writeExcelSchedule();
          doc.writeSchedule();
          doc.writeFacilitySchedule();
          JOptionPane
              .showMessageDialog(
                  null,
                  "Schedules written to schedule.html, schedule.xls, facility_schedule.html",
                  "File saved ...", JOptionPane.INFORMATION_MESSAGE, null);
        }
      }
    });
    menu.add(menuItem);

    menuItem = new JMenuItem("Export Master Schedule (html)", KeyEvent.VK_E);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    menuItem.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        if (doc != null)
        {
          doc.writeSchedule();
          JOptionPane.showMessageDialog(null,
              "Master schedule written to schedule.html", "File saved ...",
              JOptionPane.INFORMATION_MESSAGE, null);
        }
      }
    });
    menu.add(menuItem);

    menuItem = new JMenuItem("Export Master Schedule (xls)", KeyEvent.VK_X);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    menuItem.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        if (doc != null)
        {
          doc.writeExcelSchedule();
          JOptionPane.showMessageDialog(null,
              "Master schedule written to schedule.xls", "File saved ...",
              JOptionPane.INFORMATION_MESSAGE, null);
        }
      }
    });
    menu.add(menuItem);

    menuItem = new JMenuItem("Export League Schedule", KeyEvent.VK_L);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    menuItem.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {}
    });
    menu.add(menuItem);
    menuItem.setEnabled(false);

    menuItem = new JMenuItem("Export Facility Schedule", KeyEvent.VK_F);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    menuItem.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        if (doc != null)
        {
          doc.writeFacilitySchedule();
          JOptionPane.showMessageDialog(null,
              "Facility schedule written to facility_schedule.html",
              "File saved ...", JOptionPane.INFORMATION_MESSAGE, null);
        }
      }
    });
    menu.add(menuItem);

    menuItem = new JMenuItem("Export Team Schedule", KeyEvent.VK_T);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    menuItem.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {}
    });
    menuItem.setEnabled(false);
    menu.add(menuItem);

    // Build the second menu.
    menu = new JMenu(Local.get("Options"));
    menu.setMnemonic(KeyEvent.VK_O);
    menuBar.add(menu);

    useTimeStamp = new JCheckBoxMenuItem(Local.get("UseTimeStamp"));
    // ,KeyEvent.VK_U);
    useTimeStamp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    useTimeStamp.addActionListener(this);
    useTimeStamp.setEnabled(false);
    menu.add(useTimeStamp);

    useFileVersion = new JCheckBoxMenuItem(Local.get("UseVersion"));
    // ,KeyEvent.VK_U);
    useFileVersion.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    useFileVersion.addActionListener(this);
    useFileVersion.setEnabled(false);
    menu.add(useFileVersion);

    clearLog = new JMenuItem(Local.get("Clear"), KeyEvent.VK_C);
    clearLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    clearLog.addActionListener(this);
    menu.add(clearLog);
    /*
     * menuItem = new JMenuItem("Clear File History",KeyEvent.VK_F);
     * menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_F,
     * ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
     * menuItem.addActionListener(new ActionListener() { public void
     * actionPerformed(ActionEvent e) { if(fileHistory != null) fileHistory }
     * }); menu.add(clearLog);
     */

    saveLog = new JMenuItem("Save Log", KeyEvent.VK_C);
    saveLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    saveLog.addActionListener(this);
    menu.add(saveLog);

    changeLeague = new JMenuItem(Local.get("ChangeLeague"), KeyEvent.VK_L);
    changeLeague.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    changeLeague.addActionListener(this);
    menu.add(changeLeague);

    // Build the help menu
    menu = new JMenu(Local.get("Help"));
    menu.setMnemonic(KeyEvent.VK_H);
    menuBar.add(menu);

    helpHelp = new JMenuItem(Local.get("Help"), KeyEvent.VK_H);
    helpHelp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    helpHelp.addActionListener(this);
    menu.add(helpHelp);

    helpAbout = new JMenuItem(Local.get("About"), KeyEvent.VK_A);
    helpAbout.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
        ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
    helpAbout.addActionListener(this);
    menu.add(helpAbout);
    /* add toggle button to the right of the Calendar */
    menuBar.add(Box.createHorizontalGlue());
    JButton toggleButton = new JButton("Switch to Team Builder >>");
    toggleButton.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        RSMSController.toggle();
      }
    });
    menuBar.add(toggleButton);

  }

  /**
   * Displays the file chooser, pipes the file through the Parser and
   * initializes the skillOrder field of Virtue. It also writes the map file.
   * 
   * @param d
   *          The AutoScheduleDoc that is being displayed by this window.
   * @return void.
   */
  void newData()
  {
    doc = new AutoScheduleDoc();
    frame.setDoc(doc);
    st.setDoc(doc);

    useTimeStamp.setEnabled(true);
    useTimeStamp.setState(doc.getUseTimeStamp());

    useFileVersion.setEnabled(true);
    useFileVersion.setState(doc.getUseFileVersion());
  }

  /**
   * Displays the file chooser to select an AutoScheduleDoc file. If selection
   * is successful, reads the object and adds a window.
   * 
   * @return void.
   */
  void openData()
  {
    if (fc == null)
      fc = new JFileChooser(System.getProperty("user.dir"));
    fc.addChoosableFileFilter(new AutoTeamFileFilter("sched",
        "AutoSchedule files"));
    int returnVal = fc.showOpenDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION)
    {
      File file = fc.getSelectedFile();
      doOpen(file);
    }
  }

  public void doOpen(File file)
  {
    try
    {
      FileInputStream in = new FileInputStream(file);
      ObjectInputStream s = new ObjectInputStream(in);
      doc = (AutoScheduleDoc) s.readObject();

      doc.setSourceFile(file);

      st.setDoc(doc);
      frame.setDoc(doc);
      this.setTitle(Local.get("ScheduleProgramName") + " : " + doc.getName());

      doc.updateScheduleTree();

      useTimeStamp.setEnabled(true);
      useTimeStamp.setState(doc.getUseTimeStamp());

      useFileVersion.setEnabled(true);
      useFileVersion.setState(doc.getUseFileVersion());

      fileHistory.insertPathname(file.getAbsolutePath()); // Hook into
      // FileHistory
      // class

    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  void saveData()
  {
    if (doc.getSourceFile() != null)
    {
      if (doc.getSourceFile().getName().endsWith(".sched"))
      {
        doc.saveDoc(doc.getSourceFile());
        JOptionPane.showMessageDialog(null, "League " + doc.getName()
            + " saved to file " + doc.getSourceFile().getAbsolutePath(),
            "File saved ...", JOptionPane.INFORMATION_MESSAGE, null);
      }
      else
        saveDataAs();
    }
    else
      JOptionPane.showMessageDialog(null, Local.get("NoSelectionWin"), Local
          .get("Error"), JOptionPane.ERROR_MESSAGE, null);
  }

  void saveDataAs()
  {
    try
    {
      if (frame == null)
        JOptionPane.showMessageDialog(null, Local.get("NoSelectionWin"), Local
            .get("Error"), JOptionPane.ERROR_MESSAGE, null);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

    if (fc == null)
      fc = new JFileChooser(System.getProperty("user.dir"));
    fc.addChoosableFileFilter(new AutoTeamFileFilter("sche",
        "AutoSchedule files"));
    if (doc.getSourceFile() != null)
      fc.setSelectedFile(doc.getSourceFile());
    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION)
    {
      File file = fc.getSelectedFile();
      if (!file.getName().endsWith(".sched"))
      {
        file = new File(file.getPath() + ".sched");
      }
      doc.setSourceFile(file);
      doc.saveDoc(file);
      fileHistory.insertPathname(file.getAbsolutePath()); // Hook into
      // FileHistory
      // class
      JOptionPane.showMessageDialog(null, "League " + doc.getName()
          + " saved to file " + file.getAbsolutePath(), "File saved ...",
          JOptionPane.INFORMATION_MESSAGE, null);
    }

  }

  void doLogout()
  {
    RSMSController.replaceActiveFrameAndLogout(new LoginFrame(RSMSController));
  }

  void closeWindow()
  {}

  public void doUseTimeStamp()
  {
    doc.toggleUseTimeStamp();
    useTimeStamp.setState(doc.getUseTimeStamp());
  }

  public void doUseFileVersion()
  {
    doc.toggleUseFileVersion();
    useFileVersion.setState(doc.getUseFileVersion());
  }

  public void doClearLog()
  {
    if (frame != null)
      doc.clearLog();
    else
      JOptionPane.showMessageDialog(null, Local.get("NoSelectionWin"), Local
          .get("Error"), JOptionPane.ERROR_MESSAGE, null);
  }

  void doSaveLog()
  {
    try
    {
      if (frame != null)
      {
        File file = doc.writeLog();
        if (file != null)
          JOptionPane.showMessageDialog(null, "Log saved to file "
              + file.getAbsolutePath(), "File saved ...",
              JOptionPane.INFORMATION_MESSAGE, null);
      }
      else
        JOptionPane.showMessageDialog(null, Local.get("NoSelectionWin"), Local
            .get("Error"), JOptionPane.ERROR_MESSAGE, null);
    }
    catch (Exception e)
    {
      ;
    }
  }

  void doChangeLeague()
  {
    try
    {
      /*
       * if(frame != null) frame.changeLeague(); else
       * JOptionPane.showMessageDialog(null,Local.get("NoSelectionWin"),
       * Local.get("Error"), JOptionPane.ERROR_MESSAGE,null);
       */
    }
    catch (Exception e)
    {
      ;
    }
  }

  void doHelp()
  {
    if (helpBox == null)
    {
      JPanel panel = new JPanel();
      panel.setOpaque(false);
      panel.setLayout(new BorderLayout());

      JEditorPane editorPane = new JEditorPane();
      editorPane.setEditable(false);
      // create a URL object for the Help file
      String s = null;
      try
      {
        s = "jar:file:autoteam.jar!/"
        // + System.getProperty("user.dir")
            // + System.getProperty("java.class.path")
            // + "." + System.getProperty("file.separator")
            + "autoteamhelp.htm";
        URL helpURL = new URL(s);
        try
        {
          editorPane.setPage(helpURL);
        }
        catch (IOException e)
        {
          System.err.println("Attempted to read a bad URL: " + helpURL);
        }
      }
      catch (Exception e)
      {
        System.err.println("Couldn't create help URL: " + s);
      }
      JScrollPane editorScrollPane = new JScrollPane(editorPane);
      editorScrollPane
          .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      editorScrollPane.setPreferredSize(new Dimension(500, 300));

      helpBox = new JDialog(this, Local.get("AboutBoxTitle_s"), false);
      helpBox.getContentPane().setLayout(new BorderLayout());
      helpBox.getContentPane().add(editorScrollPane, BorderLayout.CENTER);

      JPanel buttonpanel = new JPanel();
      buttonpanel.setOpaque(true);
      JButton button = (JButton) buttonpanel.add(new JButton(Local
          .get("ok_button_text")));
      // panel.add(buttonpanel, BorderLayout.SOUTH);
      helpBox.getContentPane().add(buttonpanel, BorderLayout.SOUTH);
      button.addActionListener(new OkAction(helpBox));
    }
    helpBox.pack();
    Point p = this.getLocationOnScreen();
    helpBox.setLocation(p.x + this.getWidth() / 2 - helpBox.getWidth() / 2, p.y
        + this.getHeight() / 2 - helpBox.getHeight() / 2);
    helpBox.show();
  }

  class OkAction extends AbstractAction
  {
    JDialog aboutBox;

    protected OkAction(JDialog aboutBox)
    {
      super("OkAction");
      this.aboutBox = aboutBox;
    }

    public void actionPerformed(ActionEvent e)
    {
      aboutBox.setVisible(false);
    }
  }

  void doAbout()
  {
    if (aboutBox == null)
    {
      // JPanel panel = new JPanel(new BorderLayout());
      // JPanel panel = new AboutPanel(swingset);
      JPanel panel = new JPanel();
      panel.setOpaque(false);
      panel.setLayout(new BorderLayout());

      JLabel label = new JLabel(Local.get("AboutText_s"));
      panel.add(label, BorderLayout.CENTER);

      aboutBox = new JDialog(this, Local.get("AboutBoxTitle_s"), false);
      aboutBox.getContentPane().setLayout(new BorderLayout());
      aboutBox.getContentPane().add(panel, BorderLayout.CENTER);

      JPanel buttonpanel = new JPanel();
      buttonpanel.setOpaque(true);
      JButton button = (JButton) buttonpanel.add(new JButton(Local
          .get("ok_button_text")));
      panel.add(buttonpanel, BorderLayout.SOUTH);

      button.addActionListener(new OkAction(aboutBox));
    }
    aboutBox.pack();
    Point p = this.getLocationOnScreen();
    aboutBox.setLocation(p.x + this.getWidth() / 2 - aboutBox.getWidth() / 2,
        p.y + this.getHeight() / 2 - aboutBox.getHeight() / 2);
    aboutBox.show();
  }

  void doFacilityAdd()
  {
    String inputValue = JOptionPane
        .showInputDialog("Please enter a name for the facility:");
    if (inputValue != null)
    {
      doc.addFacility(new Facility(inputValue));
    }

  }

  void doFacilityDel()
  {
    Facility f = st.getSelectedFacility();
    doc.deleteFacility(f);
  }

  void doFacilityRename()
  {
    String inputValue = JOptionPane
        .showInputDialog("Please enter a name for the facility:");
    Facility f = st.getSelectedFacility();
    doc.setFacilityName(f, inputValue);
  }

  void doLeagueAdd()
  {
    String inputValue = JOptionPane
        .showInputDialog("Please enter a name for the facility:");
    if (inputValue != null)
    {
      doc.addLeague(new League(inputValue));
    }

  }

  void doLeagueDel()
  {
    doc.deleteLeague(st.getSelectedLeague());
  }

  void doLeagueRename()
  {
    String inputValue = JOptionPane
        .showInputDialog("Please enter a name for the league:");
    doc.renameLeague(st.getSelectedLeague(), inputValue);
  }

  public void actionPerformed(ActionEvent e)
  {
    JMenuItem source = (JMenuItem) (e.getSource());

    if (source == fileOpen)
      openData();
    else if (source == fileNew)
      newData();
    else if (source == fileLogout)
      doLogout();
    // else if(source == fileSave)
    // saveData();
    // else if(source == fileSaveAs)
    // saveDataAs();
    // else if(source == fileClose)
    // closeWindow();
    // / else if(source == fileExit)
    // {System.exit(0);}
    else if (source == useTimeStamp)
      doUseTimeStamp();
    else if (source == useFileVersion)
      doUseFileVersion();
    else if (source == clearLog)
      doClearLog();
    else if (source == saveLog)
      doSaveLog();
    else if (source == changeLeague)
      doChangeLeague();
    else if (source == facAdd)
      doFacilityAdd();
    else if (source == facDel)
      doFacilityDel();
    else if (source == facRename)
      doFacilityRename();
    else if (source == leagueAdd)
      doLeagueAdd();
    else if (source == leagueDel)
      doLeagueDel();
    else if (source == leagueRename)
      doLeagueRename();
    else if (source == helpHelp)
      doHelp();
    else if (source == helpAbout)
      doAbout();

  }

  public static void main(String[] args)
  {
    try
    {
      UIManager
          .setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      // UIManager.getCrossPlatformLookAndFeelClassName());
    }
    catch (Exception e)
    {}

    // Set up the localization
    String language = new String("en");
    String country = new String("US");

    Local.initialize(language, country);

    AutoScheduleDeskTop frame = new AutoScheduleDeskTop();
    frame.setVisible(true);

    if (args.length == 1)
    {
      System.out.println("Trying to open " + args[0]);
      File file = new File(args[0]);
      frame.doOpen(file);
    }
  }
}
